import {
	request
} from '@/api/request/index.js'
import cartapi from '@/api/cart/model.js'
import local_userinfo from '@/util/user/local-userinfo.js'
import local_addressinfo from '@/util/address/local_addr.js'
//用户缓存信息
let userSession = null;
let addressSession = null;
var common = {
	getAllAddress(callback, setdefault = true) {
		//用户缓存信息
		userSession = local_userinfo.getUserinfo();
		addressSession = local_addressinfo.getAddr();
		if (addressSession && userSession)
			addressSession.phone = userSession.phone
		let sessionKey = userSession ? userSession.sessionid : '';
		let city = addressSession.city ? addressSession.city.replace(/市/, '') : '上海';
		uni.showLoading({
			title: '正在加载模块...',
			mask: true
		})
		request.get({
				data: {
					city: city,
					rediskey: sessionKey,
					showtype: '',
					c: 'AddressController',
					m: 'GetList',
				}
			})
			.then(res => {
				if (res.Status == "ok") {
					let result = res.Tag || [];
					let defaultAddress = null;
					if (setdefault) {
						if (result.length > 0) {
							for (let a = 0; a < result.length; a++) {
								let ritem = result[a];
								if (ritem.IsDefault == 1) {
									defaultAddress = ritem;
									break;
								}
							}
						}
					}
					if (callback) callback(result, defaultAddress);
				} else {
					if (callback) callback([], null);
				}
			})
			.catch(error => {
				console.error(error)
			});

	},
	checkAddress(checkedaddress = null, callback) {
		if (!checkedaddress) {
			if (callback) callback();
			return
		}
		let lng = checkedaddress.Lng,
			lat = checkedaddress.Lat,
			city = checkedaddress.city,
			that = this;

		uni.showLoading({
			mask: true,
			title: '正在加载模块...'
		});
		request.get({
				data: {
					c: 'AddressController',
					m: 'CheckAddress',
					city: city,
					lat: lat,
					lng: lng
				}
			})
			.then(res => {
				if (res.Status == "ok") {
					let store = res.Tag
					if (callback) callback(store)
				} else {
					if (callback) callback('')
					uni.showModal({
						title: '无法配送',
						content: '当前地址暂未开通配送，请更新其他地址',
						confirmText: '确定',
						confirmColor: '#e64340',
						showCancel: false,
						success(res) {
							if (res.confirm) {}
						}
					})


				}
			})
			.catch(error => {
				console.error(error)
				if (callback) callback()
			});
	},
	prepareOrderCheck(commodityList, checkedaddress, callback) {
		uni.showLoading({
			mask: true,
			title: '正在加载模块...'
		});
		request.post({
				data: {
					c: 'OrderMainController',
					m: 'PrepareOrderValid',
					rediskey: userSession.sessionid,
					addressinfo: JSON.stringify(checkedaddress || ''),
					commodityInfo: JSON.stringify(commodityList)
				},
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				}
			})
			.then(res => {
				if (res.Status == "ok") {
					let result = res.Tag.result || null;
					let orderid = res.Tag.orderid;
					if (callback) callback(result, orderid);
				} else {

				}
			})
			.catch(error => {
				console.error(error)
				if (callback) callback()
			});
	},
	showToast(msg = '') {
		uni.showToast({
			icon: 'none',
			title: msg,
			mask: true
		})
	}
}

export default {
	// components: {
	// 	componentaddress
	// },
	data() {
		return {
			showAddress: false,
			delivery: {
				addresslist: [],
				checkedaddress: null,
				shippingcost: 0,
				city: '',
				address: '',
				name: '',
				phone: '',
				deliveryDateList: [],
				deliveryDate: '',
				timeList: [],
				checktime: '',
				orderid: ''
			},
			CommodityList: [],
			totalCommodityPrice: 0,
			totalCommodityDicount: 0,
			time: false,
			scrollTop: 0,
			orderRemark: '',
			showRemark: false,
			totalPrice: 0,
			pay: 0,
			totaldiscount: 0,
			timer: 0, //防止高频点击
			ismp: false,
			localaddress: addressSession,
			mapCallbackData: ''
		}
	},
	onLoad() {
		// #ifdef MP-WEIXIN
		this.ismp = true;
		uni.hideShareMenu()
		// #endif
		this.init()
	},
	onShow: function() {
		let that = this;
		let mapcallData = this.$tempaddress.state;
		if (mapcallData && mapcallData.Lat) {
			common.checkAddress(mapcallData, function(store = '') {
				that.delivery.checkedaddress = mapcallData;
				that.delivery.city = mapcallData.city;
				that.delivery.address = mapcallData.address;
				that.delivery.name = mapcallData.name;
				that.delivery.phone = mapcallData.phone;
				that.showAddress = false;
				that.delivery.checkedaddress.store = store
				
				// that.$tempaddress.commit('setTemp',{})
			})
		}
	},
	methods: {
		init() {
			let that = this;
			this.totalCommodityPrice = 0;
			this.totalCommodityDicount = 0;
			that.CommodityList = [];
			let list = cartapi.getCartList() //读取购物车数据
			let prepareCommoditylist = [];
			let callbacksecond = function(checkedaddress) {
				list.map((item, idx) => {
					if (item.Checked) {
						prepareCommoditylist.push({
							commodityId: item.CommodityId,
							packageId: item.PackageId,
							packageSupplyNo: item.PackageSupplyNo,
							num: item.Num,
							price: item.Price,
							zkPrice: item.ZkPrice
						});

						that.CommodityList.push({
							$GuidId: item.$GuidId,
							CommodityId: item.CommodityId, //商品ID
							CommodityName: item.CommodityName, //商品名称
							CommodityDesc: item.CommodityDesc, //商品优惠描述
							PackageId: item.PackageId, //选中规格的ID
							PackageSupplyNo: item.PackageSupplyNo, //选中规格的sku
							PackageName: item.PackageName, //选中规格名称
							Price: item.Price, //原价，固定不变
							ZkPrice: item.ZkPrice, //折扣后金额
							Discount: item.Discount, //优惠的金额 = （原价-折扣金额）*数量
							Num: item.Num, //数量
							City: item.City, //城市
							DetailsList: [], //详细产品
							ExpireTime: null, //过期时间
							IsFlash: item.IsFlash, //是否支持闪送
							DeliveryCity: item.DeliveryCity,
							DeliveryStore: item.DeliveryStore,
							Size: item.Size,
							img: that.$cartImgsrc.replace('{0}',item.CommodityName)
						})
					}
				});
				//视图数据绑定
				let viewCreated = function(result, orderid) {
					let timelist = result.CommonDeliveryTimelist,
						shippingcost = result.DeliveryShippingCost,
						totalPrice = result.totalPrice,
						totalDiscount = result.totalDiscout,
						now = result.Now,
						deliveryDatelist = result.ListDeliveryDate,
						supportFlash = result.SupportFlash,
						supportZsd = result.SupportZSD,
						supportUseCoupon = result.SupportUseCoupon,
						flashTimelist = result.FlashDeliveryTimelist || [],
						zsdTimelist = result.ZsdDeliveryTimelist || [];

					that.totalCommodityPrice = totalPrice;
					that.totalCommodityDicount = totalDiscount;
					that.delivery.shippingcost = shippingcost;
					that.delivery.deliveryDateList = deliveryDatelist;
					that.delivery.timeList = timelist;
					that.delivery.orderid = orderid;
					that.packPrice();
				}
				common.prepareOrderCheck(prepareCommoditylist, checkedaddress, viewCreated);
			}
			let callbackfirst = function(addresslist = [], defaultaddress = null) {
				that.delivery.addresslist = addresslist;
				that.delivery.checkedaddress = defaultaddress;
				if (defaultaddress) {
					that.delivery.city = defaultaddress.city;
					that.delivery.address = defaultaddress.address;
					that.delivery.name = defaultaddress.name;
					that.delivery.phone = defaultaddress.phone;
				}
				common.checkAddress(defaultaddress, function(store = '') {
					let checkedaddress = {
						store: store,
						city: addressSession.city ? addressSession.city.replace(/市/, '') : '上海'
					}
					if (that.delivery.checkedaddress)
						that.delivery.checkedaddress.store = store
					if (callbacksecond) callbacksecond(checkedaddress)
				})
			}
			common.getAllAddress(callbackfirst)
		},
		getAlladdress() {
			let that = this
			common.getAllAddress((result) => {
				that.delivery.addressList = result;
				that.$refs.componentaddress.addressList = result;
			}, false);
		},
		checkaddress(addr) {
			let that = this
			console.log(addr)

			common.checkAddress(addr, function(store = '') {
				that.delivery.checkedaddress = addr;
				that.delivery.city = addr.city;
				that.delivery.address = addr.address;
				that.delivery.name = addr.name;
				that.delivery.phone = addr.phone;
				that.showAddress = false;
				that.delivery.checkedaddress.store = store
			})
		},
		minusitem(cart) {
			let go = () => {
				cartapi.modify('reduce', cart)
				this.init()
			}
			if (cart.Num <= 1) {
				uni.showModal({
					title: '提示',
					content: `是否将${cart.CommodityName}从购物车移除？`,
					success(r) {
						if (r.confirm) {
							go()
						}
					}
				})
			} else go()

		},
		plusitem(cart) {
			cartapi.modify('add', cart)
			this.init()
		},
		choose(item, type, $event) {
			if (type) {
				if (this.cartList.length == 0) return;
				this.checkall = !this.checkall;
				let chackall = this.checkall
				this.cartList.map((sitem) => {
					sitem.Checked = chackall
					cartapi.modify('choose', sitem)
				})
			} else {
				item.Checked = !item.Checked
				cartapi.modify('choose', item)
			}

			this.init()
		},
		clearall($event) {
			let that = this
			if (!this.checkall) return;
			uni.showModal({
				title: '提示',
				content: `是否清空当前城市的购物车商品？`,
				success(r) {
					if (r.confirm) {
						cartapi.modify('clearall')
						that.init()
					}
				}
			})
		},
		//防止冒泡和滚动穿透
		stopPrevent() {},
		gohref(item) {
			let href = "/pages/detail/detail?cid=" + item.CommodityId + "&pid=" + item.PackageId;
			uni.navigateTo({
				url: href
			})
		},
		showBZ: function() {
			this.showRemark = true;
		},
		closeBz: function() {
			this.showRemark = false;
		},
		showTime: function() {
			this.time = true;
		},
		closeTime: function() {
			this.time = false;
		},
		chooseTime: function(item) {
			this.delivery.deliveryDate = item.deliveryDate
			// this.delivery.checktime=''
		},
		choosePsfs: function(index) {
			if (index != this.psfs) {
				this.psfs = index;
			}
		},
		chooseClock: function(item) {
			this.delivery.checktime = item.time;
		},
		packPrice() {
			let commodityPrice = this.totalCommodityPrice;
			let commodityDiscount = this.totalCommodityDicount;
			let shippingcost = this.delivery.shippingcost;

			let total = commodityPrice + shippingcost;
			this.totalPrice = total + commodityDiscount;
			this.pay = total;
			this.totaldiscount = commodityDiscount;
		},
		//订单提交
		submit() {
			let that = this;
			//配送信息组件
			let deliveryInfo = {
				date: this.delivery.deliveryDate,
				time: this.delivery.checktime,
				shippingcost: this.delivery.shippingcost,
				addr: this.delivery.checkedaddress,
				channel_from: this.ismp ? 'MP' : 'H5',
				remarks: this.orderRemark,
				orderid: this.delivery.orderid
			};
			if (deliveryInfo.addr) {
				if (!deliveryInfo.addr.name || !deliveryInfo.addr.phone || !deliveryInfo.addr.address) return common.showToast(
					'请完善收货信息')
			} else return common.showToast('请完善收货信息')
			if (!deliveryInfo.date) return common.showToast('请选择配送日期')
			if (!deliveryInfo.time) return common.showToast('请选择配送时间段')

			let commodityList = this.CommodityList,
				newcommodityList = [];
			commodityList.map((citem) => {
				newcommodityList.push({
					commodityId: citem.CommodityId,
					packageId: citem.PackageId,
					packageSupplyNo: citem.PackageSupplyNo,
					num: citem.Num
				})
			});
			//防止高频点击
			if (this.timer == 1) return common.showToast('请等待服务器处理结果')
			this.timer = 1;
			uni.showLoading({
				mask: true,
				title: '订单提交中...'
			});
			request.post({
					data: {
						c: 'OrderMainController',
						m: 'AddOrderOne',
						rediskey: userSession.sessionid,
						addressinfo: JSON.stringify(deliveryInfo),
						commodityInfo: JSON.stringify(newcommodityList)
					},
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					}
				})
				.then(res => {
					that.timer = 0
					if (res.Status == "ok") {
						let result = res.Tag;
						cartapi.modify('clearall');
						uni.redirectTo({
							url: '../../pages/payment/payment?oid=' + result
						})
					} else {
						common.showToast(res.Msg);
					}
				})
				.catch(error => {
					that.timer = 0
					console.error(error)
				});
		}
	},
	watch: {
		totalPrice: function() {

		}
	}
};
